package com.moco.launcher.http;

import android.content.Context;
import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.moco.launcher.R;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

public class CustomHttpClient {
	private static String TAG = "CustomHttpClient";
	private static final String CHARSET_UTF8 = HTTP.UTF_8;
	private static final String CHARSET_GB2312 = "GB2312";
	private static DefaultHttpClient customerHttpClient;
	private static CookieStore cookieStore;

	public static CookieStore getCookieStore() {
		return cookieStore;
	}

	private CustomHttpClient() {

	}

	/**
	 * HttpClient post鏂规硶
	 * 
	 * @param url
	 * @param nameValuePairs
	 * @return
	 * @throws IOException
	 */
	public static String PostFromWebByHttpClient(Context context, String url,
			NameValuePair... nameValuePairs) throws IOException {
		try {
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			if (nameValuePairs != null) {
				for (int i = 0; i < nameValuePairs.length; i++) {
					params.add(nameValuePairs[i]);
				}
			}
			UrlEncodedFormEntity urlEncoded = new UrlEncodedFormEntity(params,
					CHARSET_GB2312);
			Log.i(TAG, url);
			HttpPost httpPost = new HttpPost(url);
			httpPost.setEntity(urlEncoded);
			DefaultHttpClient client = getHttpClient(context);
			if (cookieStore != null) {
				client.setCookieStore(cookieStore);
			}
			HttpResponse response = client.execute(httpPost);
			if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
				throw new RuntimeException("璇锋眰澶辫触");
			}
			HttpEntity resEntity = response.getEntity();
			cookieStore = client.getCookieStore();
			return (resEntity == null) ? null : EntityUtils.toString(resEntity,
					CHARSET_UTF8);
		} catch (UnsupportedEncodingException e) {

			return null;
		} catch (ClientProtocolException e) {
			return null;
		} catch (IOException e) {
			return null;
			// throw new RuntimeException(context.getResources().getString(
			// R.string.httpError), e);
		}
	}

	public static String getFromWebByHttpClient(Context context, String url,
			NameValuePair... nameValuePairs) throws Exception {
		// http鍦板潃
		// String httpUrl =
		// "http://192.168.1.110:8080/httpget.jsp?par=HttpClient_android_Get";
		StringBuilder sb = new StringBuilder();
		sb.append(url);
		if (nameValuePairs != null && nameValuePairs.length > 0) {
			sb.append("?");
			for (int i = 0; i < nameValuePairs.length; i++) {
				if (i > 0) {
					sb.append("&");
				}
				sb.append(String.format("%s=%s", nameValuePairs[i].getName(),
						nameValuePairs[i].getValue()));
			}
		}

		// HttpGet杩炴帴瀵硅薄
		HttpGet httpRequest = new HttpGet(sb.toString());
		// 鍙栧緱HttpClient瀵硅薄
		DefaultHttpClient httpclient = getHttpClient(context);
		if (cookieStore != null) {
			httpclient.setCookieStore(cookieStore);
		}

		// 璇锋眰HttpClient锛屽彇寰桯ttpResponse
		HttpResponse httpResponse = httpclient.execute(httpRequest);

		// 璇锋眰鎴愬姛
		if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
			throw new RuntimeException(context.getResources().getString(
					R.string.httpError));
		}
		cookieStore = httpclient.getCookieStore();

		return EntityUtils.toString(httpResponse.getEntity());

	}

	/**
	 * 鍒涘缓httpClient瀹炰緥
	 * 
	 * @return
	 * @throws Exception
	 */
	private static synchronized DefaultHttpClient getHttpClient(Context context) {
		HttpParams params = new BasicHttpParams();

		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		HttpProtocolParams.setContentCharset(params, CHARSET_UTF8);
		HttpProtocolParams.setUseExpectContinue(params, true);

		HttpProtocolParams
				.setUserAgent(
						params,
						"Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "
								+ "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");
		// 瓒呮椂璁剧疆
		/* 浠庤繛鎺ユ睜涓彇杩炴帴鐨勮秴鏃舵椂锟� */
		ConnManagerParams.setTimeout(params, 10000);
		/* 杩炴帴瓒呮椂 */
		int ConnectionTimeOut = 30000;
		if (!HttpUtil.isWifiDataEnable(context)) {
			ConnectionTimeOut = 100000;
		}
		HttpConnectionParams.setConnectionTimeout(params, ConnectionTimeOut);
		/* 璇锋眰瓒呮椂 */
		HttpConnectionParams.setSoTimeout(params, 40000);
		// 璁剧疆鎴戜滑鐨凥ttpClient鏀寔HTTP鍜孒TTPS涓ょ妯″紡
		SchemeRegistry schReg = new SchemeRegistry();
		schReg.register(new Scheme("http", PlainSocketFactory
				.getSocketFactory(), 80));
		schReg.register(new Scheme("https",
				SSLSocketFactory.getSocketFactory(), 443));

		// 浣跨敤绾跨▼瀹夊叏鐨勮繛鎺ョ鐞嗘潵鍒涘缓HttpClient
		ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
				params, schReg);
		customerHttpClient = new DefaultHttpClient(conMgr, params);
		return customerHttpClient;
	}
}
